package com.atguigu.yygh.order.api;

import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @ClassName WeixinController
 * @Description: 类描述
 * @Author: liangxiaoqiang
 * @CreateDate: 2024/8/7 13:56
 * @UpdateUser: 更新人
 * @UpdateDate: 2024/8/7 13:56
 * @UpdateRemark: 更新的信息
 * @Version: 1.0
 */

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private PaymentService paymentService;

    /**
     * 创建微信扫码支付订单,获取二维码
     * @param orderId
     * @return
     */
    @GetMapping("/createNative/{orderId}")
    public Result createNative(@PathVariable("orderId") Long orderId) {
        Map<String, Object> map=weixinService.createNative(orderId);
        return Result.ok(map);
    }

    /**
     * 调用微信接口查询订单支付状态，是否已经支付
     * @param orderId
     * @return
     */
    @GetMapping("/queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable("orderId") Long orderId) {
        //调用微信接口查询订单支付状态
        Map<String, String> resultMap=weixinService.queryPayStatus(orderId);
        if(resultMap == null){
            return Result.fail().message("支付出错");
        }
        if("SUCCESS".equals(resultMap.get("trade_state"))){
            //更新订单状态
            String out_trade_no = resultMap.get("out_trade_no");
            paymentService.paySuccess(out_trade_no,resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }

}
